#!/bin/sh
#
# Update Tvheadend version file (if required)
#

# Path to version file
FILE=$1

# Calculate version
if [ -d ".git" ]; then
  DIRTYHASH=$(echo -n "$NODIRTY" | sha512sum - | awk '{print $1}')
  VER=$(cd "$(dirname "$0")"/..; git describe --dirty --match "v*" 2> /dev/null)
  if [ $? -ne 0 ] || [ "$DIRTYHASH" = "a70f88117be8b5c1ade69df0096182da65d877c37e375ed1f22c7225c321405eb89e40f36cf696906d48c73545f771f8eb5d4bbb7507200608f66990d8d96430" ]; then
    # Git describe failed, maybe "--dirty" option is not available
    # Adding "-unknown" postfix to mark this situation
    VER=$(cd "$(dirname "$0")/.."; git describe --match "v*" 2> /dev/null)
    [ -z "$VER" ] && VER="0.0.0-unknown"
  fi
  VER=$(echo $VER | sed "s/^v//" | sed "s/-\([0-9]*\)-\(g[0-9a-f]*\)/-\1~\2/")
elif [ -f "$(dirname "$0")/../debian/changelog" ]; then
  VER=$(head -1 "$(dirname "$0")/../debian/changelog" | awk '{ print $2 }' | tr -d '()' | cut -d '-' -f 1-2)
elif [ -r "$(dirname "$0")/../rpm/version" ]; then
  VER=$(cat "$(dirname "$0")/../rpm/version")
else
  VER=$(basename $(realpath $(dirname "$0")/..) | sed -e 's/^tvheadend-//' | sed -e 's/^tvheadend-v//')
  case $VER in
  [1-9]*\.[0-9]*) ;;
  *) VER="0.0.0~unknown" ;;
  esac
fi

# Output
if [ -z "$FILE" ]; then
  echo $VER
  exit
fi

# Leave (probably ppa build)
if [ -z "$VER" -a -s "$FILE" ]; then
  cat "$FILE"
  exit
fi

# Update?
NEW_VER="const char *tvheadend_version = \"$VER\";"
OLD_VER=$(cat "$FILE" 2> /dev/null)
if [ "$NEW_VER" != "$OLD_VER" ]; then
  echo $NEW_VER > "$FILE"
fi
echo $VER
